package com.wx.bootsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.bootsecurity.entity.WxUser;
import com.wx.bootsecurity.entity.vo.LoginParams;
import com.wx.bootsecurity.mapper.WxUserMapper;
import com.wx.bootsecurity.service.WxUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wx.bootsecurity.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author 阿尔法哲
 * @since 2021-07-22
 */
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements WxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public WxUser findByUserName(String username) {
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        WxUser wxUser = wxUserMapper.selectOne(queryWrapper);
        return wxUser;
    }

    @Override
    public String tologin(LoginParams loginParams) {
        String username = loginParams.getUsername();
        Assert.notNull(username,"账号必须不能为空");
        String password = loginParams.getPassword();
        Assert.notNull(password,"密码必须不能为空");
        WxUser userByName = findByUserName(username);
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        if(matches){
            return jwtTokenUtil.generateToken(userByName);
        }
        return null;
    }
}
